import {memo} from "react";
import {useDispatch, useSelector, shallowEqual} from "react-redux";
import {addNumberAction, changeMessageAction, subNumberAction} from "./store/modules/count";
import {Filter} from "./Filter";

const Home = memo(function () {
    // 性能优化，使用redux hook 默认比较的是整个state,因此App组件count改变，Home组件跟着渲染，这时只需在useSelector加上shallowEqual函数即可修复home组件意外渲染(第二个参数shallowEqual将映射出来的对象每次进行浅层比较，如果相同不重新渲染，否则重新渲染)
    const {message} = useSelector((state) => ({message: state.count.message}), shallowEqual)
    const dispatch = useDispatch();
    console.log('home组件渲染')
    const changeMessage = (message) => {
        dispatch(changeMessageAction(message))
    }

    return (
        <div>
            <div>Home组件</div>
            <div>message:{message}</div>
            <button onClick={() => changeMessage(Math.random() + '')}>改变message</button>
        </div>
    )
})

const AppFunc = memo(function AppFunc() {
    // 使用useSelector将redux中store数据映射到组件中
    // 性能优化，使用redux hook 默认比较的是整个state,因此Home组件message改变，App组件跟着渲染，这时只需在useSelector加上shallowEqual函数即可修复home组件意外渲染(第二个参数shallowEqual将映射出来的对象每次进行浅层比较，如果相同不重新渲染，否则重新渲染)
    const {count} = useSelector((state) => ({count: state.count.count}), shallowEqual)
    const dispatch = useDispatch();

    const addNumber = (num) => {
        dispatch(addNumberAction(num))
    }
    const subNumber = (num) => {
        dispatch(subNumberAction(num))
    }

    console.log('App组件渲染')

    return (
        <div>
            <div>当前计数：{count}</div>
            <button onClick={() => addNumber(1)}>+1</button>
            <button onClick={() => subNumber(1)}>-1</button>
            <Home/>
            <Filter/>
        </div>
    )
})

export default AppFunc;